﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Infrastructure;
using PickingBusiness;
using Picking.Common;
using Infrastructure.Util;

namespace Picking_Winform
{
    public partial class LightsAndDNoSetupView : FormBase
    {
        private LightAndDNoSetupModel model = new LightAndDNoSetupModel();
        private SebangoAndDNoSetupModel modelSebangoAndDNo = new SebangoAndDNoSetupModel();
        private int MaxLightAddress = ConfigInfo.MaxLightAddress1;
        private int MinLightAddress = ConfigInfo.MinLightAddress1;

        /// <summary>
        /// Constructor
        /// </summary>
        public LightsAndDNoSetupView()
        {
            InitializeComponent();
            this.Controls.Add(base.txtTitle);
            this.comboBox1.Items.Clear();
            this.comboBox1.Items.AddRange(base.items);
            this.comboBox1.SelectedIndex = 0;
        }

        /// <summary>
        /// Get Form Width
        /// </summary>
        /// <returns></returns>
        protected override int GetFormWidth()
        {
            return 820;
        }

        /// <summary>
        /// Set Form Title
        /// </summary>
        private void SetFormTitle()
        {
            this.Text = txtTitle.Text = "棚灯和图纸号的设定";
        }

        /// <summary>
        /// Form Shown
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LightsAndDNoSetupView_Shown(object sender, EventArgs e)
        {
            this.SetFormTitle();
        }

        /// <summary>
        /// Form Load
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LightsAndDNoSetupView_Load(object sender, EventArgs e)
        {
            this.GetLightAndDNoSetup();
        }

        private string GetLineCode()
        {
            string lineCode = ConfigInfo.LineCodeA;

            if (this.comboBox1.SelectedIndex == 0)
            {
                lineCode = ConfigInfo.LineCodeA;
            }
            else if (this.comboBox1.SelectedIndex == 1)
            {
                lineCode = ConfigInfo.LineCodeB;
            }
            else if (this.comboBox1.SelectedIndex == 2)
            {
                lineCode = ConfigInfo.LineCodeC;
            }

            return lineCode;
        }

        /// <summary>
        /// Get Light And DNo Setup From Database
        /// </summary>
        private void GetLightAndDNoSetup()
        {
            string lineCode = this.GetLineCode();

            this.model = Configuration.GetLightAndDNoSetup(lineCode);
            this.modelSebangoAndDNo = Configuration.GetSebangoAndDNoSetup(lineCode);

            this.FormatLightNo(this.model.LightAndDNoSetupTable, true);

            this.grdLightAndDNoSet.DataSource = this.model.LightAndDNoSetupTable;

        }

        /// <summary>
        /// Format Light No
        /// </summary>
        /// <param name="table"></param>
        /// <param name="isFormat"></param>
        private void FormatLightNo(DataTable table, bool isFormat)
        {
            if (isFormat)
            {
                foreach (DataRow row in table.Rows)
                {
                    row["Light_No"]
                        = int.Parse(row["Light_No"].ToString()).ToString("0000");
                }
            }
            else
            {
                foreach (DataRow row in table.Rows)
                {
                    row["Light_No"]
                        = int.Parse(row["Light_No"].ToString());
                }
            }
        }

        /// <summary>
        /// Do Validation
        /// </summary>
        /// <returns></returns>
        private bool DoValidation(bool isSave)
        {
            List<int> lightNumbers = new List<int>();
            List<string> designNoList = new List<string>();

            foreach (DataRow row in this.model.LightAndDNoSetupTable.Rows)
            {
                int lightNumber = 0;

                string lightNo = row["Light_No"].ToString().Trim();

                if (string.IsNullOrEmpty(lightNo))
                {
                    if (isSave)
                    {
                        MessageBox.Show("棚灯号不能为空!",
                                        "验证",
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Warning);
                        return false;
                    }
                }
                else
                {
                    if (!int.TryParse(lightNo, out lightNumber))
                    {
                        MessageBox.Show("棚灯号必须是个整型数值!",
                                        "验证",
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Warning);

                        return false;
                    }

                    if (lightNumber > this.MaxLightAddress)
                    {
                        MessageBox.Show("棚灯号必须小于或等于最大棚灯号：" + this.MaxLightAddress.ToString() + "!",
                                        "验证",
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Warning);

                        return false;
                    }

                    if (lightNumber < this.MinLightAddress)
                    {
                        MessageBox.Show("棚灯号必须大于或等于最小棚灯号：" + this.MinLightAddress.ToString() + "!",
                                        "验证",
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Warning);

                        return false;
                    }

                    if (!lightNumbers.Contains(lightNumber))
                    {
                        lightNumbers.Add(lightNumber);
                    }
                    else
                    {
                        MessageBox.Show("棚灯号（" + lightNumber.ToString() + "）不能重复!",
                                        "验证",
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Warning);
                        return false;
                    }
                }


                string designNo = row["Design_No"].ToString().Trim();

                if (string.IsNullOrEmpty(designNo))
                {
                    if (isSave)
                    {
                        MessageBox.Show("图纸号不能为空!",
                                        "验证",
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Warning);
                        return false;
                    }
                }
                else
                {
                    if (!designNoList.Contains(designNo))
                    {
                        designNoList.Add(designNo);
                    }
                    else
                    {
                        MessageBox.Show("图纸号（" + designNo + "）不能重复!",
                                        "验证",
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Warning);
                        return false;
                    }
                }
            }

            return true;
        }


        /// <summary>
        /// Validate Grid Data
        /// </summary>
        /// <returns></returns>
        private bool ValidateGridData(int colIndex, int rowIndex)
        {
            if (this.grdLightAndDNoSet[colIndex, rowIndex].Value == null)
            {
                return true;
            }

            string cellValue = string.Empty;

            if (this.grdLightAndDNoSet[colIndex, rowIndex].Value != null)
            {
                cellValue = this.grdLightAndDNoSet[colIndex, rowIndex].Value.ToString();
            }

            if (string.IsNullOrEmpty(cellValue))
            {
                return true;
            }

            List<int> lightNumbers = new List<int>();
            List<string> designNoList = new List<string>();

            // 验证棚灯号
            if (string.Equals(this.grdLightAndDNoSet.Columns[colIndex].Name, "colLightNumber"))
            {
                int lightNumber = 0;

                if (!int.TryParse(cellValue, out lightNumber))
                {
                    MessageBox.Show("棚灯号必须是个整型数值!",
                                    "验证",
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Warning);

                    return false;
                }

                if (lightNumber > this.MaxLightAddress)
                {
                    MessageBox.Show("棚灯号必须小于或等于最大棚灯号：" + this.MaxLightAddress.ToString() + "!",
                                    "验证",
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Warning);

                    return false;
                }

                if (lightNumber < this.MinLightAddress)
                {
                    MessageBox.Show("棚灯号必须大于或等于最小棚灯号：" + this.MinLightAddress.ToString() + "!",
                                    "验证",
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Warning);

                    return false;
                }

                for (int i = 0; i < this.grdLightAndDNoSet.Rows.Count - 1; i++)
                {
                    int temp = 0;

                    string cellValueTemp = this.grdLightAndDNoSet[colIndex, i].Value.ToString();

                    if (int.TryParse(cellValueTemp, out temp))
                    {
                        if (!lightNumbers.Contains(temp))
                        {
                            lightNumbers.Add(temp);
                        }
                        else
                        {
                            MessageBox.Show("棚灯号（" + temp.ToString() + "）不能重复!",
                                            "验证",
                                            MessageBoxButtons.OK,
                                            MessageBoxIcon.Warning);
                            return false;
                        }
                    }
                }
            }

            // 验证图纸号
            if (string.Equals(this.grdLightAndDNoSet.Columns[colIndex].Name, "colDesignNumber"))
            {
                for (int i = 0; i < this.grdLightAndDNoSet.Rows.Count - 1; i++)
                {
                    string designNo = this.grdLightAndDNoSet[colIndex, i].Value.ToString().Trim();

                    if (!string.IsNullOrEmpty(designNo))
                    {
                        if (!designNoList.Contains(designNo))
                        {
                            designNoList.Add(designNo);
                        }
                        else
                        {
                            MessageBox.Show("图纸号（" + designNo + "）不能重复!",
                                            "验证",
                                            MessageBoxButtons.OK,
                                            MessageBoxIcon.Warning);
                            return false;
                        }
                    }
                }
            }

            return true;
        }

        /// <summary>
        /// Is DNo Used By Sebango
        /// </summary>
        /// <param name="DNo"></param>
        /// <returns></returns>
        private bool IsDNoUsedBySebango(string DNo)
        {
            if (this.modelSebangoAndDNo.SebangoAndDNoSetupTable == null)
            {
                return false;
            }

            bool isDNoUsed = false;

            for (int i = this.modelSebangoAndDNo.SebangoAndDNoSetupTable.Rows.Count - 1; i >= 0; i--)
            {
                string sebangoDNo
                    = this.modelSebangoAndDNo.SebangoAndDNoSetupTable.Rows[i]["Design_No"].ToString().Trim();

                if (string.Equals(sebangoDNo, DNo))
                {
                    isDNoUsed = true;
                    break;
                }
            }

            return isDNoUsed;
        }

        /// <summary>
        /// Remove Sebango And DNo
        /// </summary>
        private void RemoveSebangoAndDNo()
        {
            if (this.modelSebangoAndDNo.SebangoAndDNoSetupTable == null)
            {
                return;
            }

            for (int i = this.modelSebangoAndDNo.SebangoAndDNoSetupTable.Rows.Count - 1; i >= 0; i--)
            {
                bool isDNoDeleted = true;

                string sebangoDNo
                    = this.modelSebangoAndDNo.SebangoAndDNoSetupTable.Rows[i]["Design_No"].ToString().Trim();

                foreach (DataRow row in this.model.LightAndDNoSetupTableCopy.Rows)
                {
                    if (string.Equals(sebangoDNo, row["Design_No"].ToString().Trim()))
                    {
                        isDNoDeleted = false;
                        break;
                    }
                }

                if (isDNoDeleted)
                {
                    this.modelSebangoAndDNo.SebangoAndDNoSetupTable.Rows.RemoveAt(i);
                }
            }
        }

        /// <summary>
        /// Save Event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Click(object sender, EventArgs e)
        {
            this.btnSave.Focus();

            this.grdLightAndDNoSet.EndEdit();

            if (!this.DoValidation(true))
            {
                return;
            }

            this.model.LightAndDNoSetupTableCopy
                = this.model.LightAndDNoSetupTable.Copy();

            this.FormatLightNo(this.model.LightAndDNoSetupTableCopy, false);

            string lineCode = this.GetLineCode();

            bool result = Configuration.SaveLightAndDNoSetup(this.model, lineCode);

            if (result)
            {
                this.RemoveSebangoAndDNo();
                Configuration.SaveSebangoAndDNoSetup(this.modelSebangoAndDNo, lineCode);
                MessageBox.Show("保存成功!", "保存", MessageBoxButtons.OK, MessageBoxIcon.Information);
                OfficeHelper.ExportCSV((grdLightAndDNoSet.DataSource as DataTable), System.Configuration.ConfigurationManager.AppSettings["CSVFilePath"]);
            }
            else
            {
                MessageBox.Show("保存失败!", "保存", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// Cancel Event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.btnCancel.Focus();

            this.GetLightAndDNoSetup();
        }

        /// <summary>
        /// Return Event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnReturn_Click(object sender, EventArgs e)
        {
            this.CloseCurrentWindow();
        }

        /// <summary>
        /// Cell End Edit
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void grdLightAndDNoSet_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (this.btnCancel.Focused)
            {
                return;
            }

            if (e.ColumnIndex < 0)
            {
                return;
            }

            if (e.RowIndex < 0)
            {
                return;
            }

            if (!this.btnSave.Focused)
            {
                this.ValidateGridData(e.ColumnIndex, e.RowIndex);
            }
        }

        /// <summary>
        /// Cell Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void grdLightAndDNoSet_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex < 0)
            {
                return;
            }

            if (e.RowIndex < 0)
            {
                return;
            }

            if (string.Equals(this.grdLightAndDNoSet.Columns[e.ColumnIndex].Name, "colDelete"))
            {
                if (e.RowIndex < this.grdLightAndDNoSet.NewRowIndex)
                {
                    bool isToDelete = true;

                    string DNo = string.Empty;

                    if ((this.grdLightAndDNoSet["colDesignNumber", e.RowIndex] != null)
                        && (this.grdLightAndDNoSet["colDesignNumber", e.RowIndex].Value != null))
                    {
                        DNo = this.grdLightAndDNoSet["colDesignNumber", e.RowIndex].Value.ToString().Trim();
                    }

                    if (this.IsDNoUsedBySebango(DNo))
                    {
                        DialogResult result
                            = MessageBox.Show("该图纸号已被使用，是否确定删除？",
                                              "提示",
                                              MessageBoxButtons.YesNo,
                                              MessageBoxIcon.Question);

                        if (result == System.Windows.Forms.DialogResult.Yes)
                        {
                            isToDelete = true;
                        }
                        else
                        {
                            isToDelete = false;
                        }
                    }

                    if (isToDelete)
                    {
                        this.grdLightAndDNoSet.Rows.RemoveAt(e.RowIndex);
                        this.grdLightAndDNoSet.Update();
                        this.grdLightAndDNoSet.EndEdit();
                    }
                }
            }
        }

        /// <summary>
        /// Cell Formatting
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void grdLightAndDNoSet_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (this.btnCancel.Focused)
            {
                return;
            }

            if (e.ColumnIndex < 0)
            {
                return;
            }

            if (e.RowIndex < 0)
            {
                return;
            }

            if (string.Equals(this.grdLightAndDNoSet.Columns[e.ColumnIndex].Name, "colLightNumber"))
            {
                int temp = 0;

                if (e.Value != null)
                {
                    string cellValue = e.Value.ToString();

                    if (int.TryParse(cellValue, out temp))
                    {
                        e.Value = int.Parse(cellValue).ToString("0000");
                    }
                }
            }
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.comboBox1.SelectedIndex == 0)
            {
                this.MaxLightAddress = ConfigInfo.MaxLightAddress1;
                this.MinLightAddress = ConfigInfo.MinLightAddress1;
            }
            else if (this.comboBox1.SelectedIndex == 1)
            {
                this.MaxLightAddress = ConfigInfo.MaxLightAddress2;
                this.MinLightAddress = ConfigInfo.MinLightAddress2;
            }
            else if (this.comboBox1.SelectedIndex == 2)
            {
                this.MaxLightAddress = ConfigInfo.MaxLightAddress3;
                this.MinLightAddress = ConfigInfo.MinLightAddress3;
            }

            this.GetLightAndDNoSetup();
        }
    }
}
